package git.soulbgm.jacob;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import java.io.File;

/**
 * 使用jacob进行pdf的转换
 *
 * @author SoulBGM
 * @version 1.0
 * @date 2020/5/19 23:17
 */
public class PdfConvert {

    public static boolean wordToPdf(String inputFile, String pdfFile) {
        try {
            // 打开word应用程序
            ActiveXComponent app = new ActiveXComponent("Word.Application");
            // 设置word不可见
            app.setProperty("Visible", false);
            // 获得word中所有打开的文档,返回Documents对象
            Dispatch docs = app.getProperty("Documents").toDispatch();
            // 调用Documents对象中Open方法打开文档，并返回打开的文档对象Document
            Dispatch doc = Dispatch.call(docs, "Open", inputFile, false, true)
                    .toDispatch();
            // 调用Document对象的SaveAs方法，将文档保存为pdf格式
            /*
             * Dispatch.call(doc, "SaveAs", pdfFile, 17);
             */
            // word保存为pdf格式宏，值为17
            Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, 17);
            // 关闭文档
            Dispatch.call(doc, "Close", false);
            // 关闭word应用程序
            app.invoke("Quit", 0);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean excelToPdf(String inputFile, String pdfFile) {
        try {
            ActiveXComponent app = new ActiveXComponent("Excel.Application");
            app.setProperty("Visible", false);
            app.setProperty("AutomationSecurity", new Variant(3));
            Dispatch excels = app.getProperty("Workbooks").toDispatch();
            Dispatch excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch();
            Dispatch.call(excel, "ExportAsFixedFormat", 0, pdfFile);
            Dispatch.call(excel, "Close", false);
            app.invoke("Quit");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static boolean pptToPdf(String inputFile, String pdfFile) {
        try {
            // 打开PPT应用程序
            ActiveXComponent app = new ActiveXComponent("PowerPoint.Application");
            Dispatch ppts = app.getProperty("Presentations").toDispatch();
            Dispatch ppt = Dispatch.call(ppts, "Open", inputFile, true, true, false).toDispatch();
            Dispatch.call(ppt, "SaveAs", pdfFile, 32);
            Dispatch.call(ppt, "Close");
            app.invoke("Quit");
            return true;
        } catch (Exception e) {
            return false;
        }
    }

}
